package com.ly.gof.structure.proxy.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author liuyang
 * @des 代理类 实现jdk的InvocationHandler接口
 * @Version 1.0
 * @Date: 21/07/2021 15:18
 */
public class ProxyHandler implements InvocationHandler {
    private Subject target;

    public ProxyHandler() {
    }

    public ProxyHandler(Subject target) {
        this.target = target;
    }

    public Subject getInstance(Subject target) {
        this.target = target;
        Class<?> clazz = target.getClass();
        return (Subject)Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
    }

    public void preRequest() {
        System.out.println("访问真实主题之前的预处理。");
    }

    public void postRequest() {
        System.out.println("访问真实主题之后的后续处理。");
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        preRequest();
        Object result = method.invoke(this.target, args);
        postRequest();
        return result;
    }
}
